﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using EvoGame.Core.Interfaces;

namespace EvoGame.Core.Components
{
	public class PluginHost : IPluginHost
	{
		public Dictionary<string, IPluggable> RegisteredPlugins { get { return registered; } }
		protected List<IPluggable> plugins = new List<IPluggable>();
		private Dictionary<string, IPluggable> registered = new Dictionary<string, IPluggable>();

		public virtual void LoadFromDLL(string path)
		{
			FileInfo fi = new FileInfo(path);
			LoadFromDLL(fi);
		}

		public virtual void LoadFromDLL(FileInfo fi)
		{
			Assembly assem = Assembly.LoadFile(fi.FullName);
			Type[] types = assem.GetTypes();

			foreach (Type plugin in types)
			{
				if (!typeof(IPluggable).IsAssignableFrom(plugin)) continue;
				plugins.Add((IPluggable)Activator.CreateInstance(plugin, this));
			}
		}

		public virtual bool Register(IPluggable plugin)
		{
			if (plugin.Load())
			{
				registered.Add(plugin.Name, plugin);
				if (EvoApp.Debug)
					EvoApp.Debug.Output = "Plugin registered: " + plugin.Name;
				return true;
			}
			else
			{
				if (EvoApp.Debug)
					EvoApp.Debug.Output = "Plugin failed to register: " + plugin.Name;
				return false;
			}
		}
	}
}
